define(function(require){
  'use strict';
  var _const = require('seajs/fn/fnConst');
  var fnRtpSocketHandler = require('seajs/fn/fnRtpSocketHandler');
  var $ = require('seajs/jquery.min');
  var fnUtils = require('seajs/fn/fnUtils');

  var rtpSocket = function(uid){
  	this.ws = undefined;
    this.slidebar = undefined;

  	this.uid = uid;
    this.cid = undefined;
    this.sid = undefined;

    this.destip = undefined;        //aip
    this.destport = undefined;      //aport
    this.payloadtype = undefined;   //atype
    this.sendflag = undefined;      //0- 不发送rtp语音，1-发送rtp语音

    this.recvPtt = 0;

    this.isInit = false;

    this.pttKey = undefined;
  } 
  rtpSocket.prototype.setSlidebar = function(slidebar){
    this.slidebar = slidebar;
  }
  rtpSocket.prototype.init = function(onSuccess){
  	var self = this;
  	if(self.uid){
      self.ws = new WebSocket('ws://'
        + _const.RTP_WS.CONFIG.HOST + ':'
        + _const.RTP_WS.CONFIG.PORT + '/'
        + _const.RTP_WS.CONFIG.PATH);
      
  	  self.ws.onopen = function(){
        if(self.isInit){
          self.accessRtp(0);
        }
        self.isInit = true;
  	  	self.onmessage();
        self.onMouseEvent();
        self.onPttKeyDown();
        self.onPttKeyUp();
  	  }
      self.onclose();
      self.onerror();
      onSuccess();
  	}
  }

  rtpSocket.prototype.send = function(msg){
  	var self = this;
  	if(self.ws.readyState == WebSocket.OPEN && msg){
  	  var _msg = JSON.stringify(msg);
      console.log('<<<<<<<<<<<<<<<<<<< RTP start <<<<<<<<<<<<<<<<<<<<<<');
      console.log(_msg);
      console.log('<<<<<<<<<<<<<<<<<<< RTP end <<<<<<<<<<<<<<<<<<<<<<<<');
  	  self.ws.send(_msg);
  	}else{
      console.log('connection to agent lost.');
    }
  }

  rtpSocket.prototype.onmessage = function(){
  	var self = this;
  	self.ws.onmessage = function(evt){
      var msg = JSON.parse(event.data);
      console.log('############## RTP start ################');
      console.log(msg);
      console.log('############## RTP end ################');
      if(msg.cmd === undefined){
        return;
      }
      switch(msg.cmd){
        // 8001 
        case _const.RTP_WS.EVENT_TYPE.ACCESS.RES:
          fnRtpSocketHandler.accessRtpHandler(self, msg);
          break;
        // 8002
        case _const.RTP_WS.EVENT_TYPE.STOP_SEND.RES:
          fnRtpSocketHandler.stopRtpHandler(self, msg);
          break;
        // 8003
        case _const.RTP_WS.EVENT_TYPE.START_SEND.RES:
          fnRtpSocketHandler.sendRtpHandler(self, msg);
          break;
        // 4
        case _const.RTP_WS.EVENT_TYPE.RECV_PTT.RES:
          fnRtpSocketHandler.recvPttHandler(self, msg);
          break;
        default:
          fnRtpSocketHandler.otherHandler(msg);
      }
  	}
  }

  rtpSocket.prototype.onclose = function(){
    var self = this;
    // self.ws.onclose = function(){
    //   if(!self.isInit){
    //     alert('RTP插件未开启或异常, 点击确定返回登陆页');
    //     location.href = 'login.html';
    //   }else{
    //     console.log('RTP插件未开启或异常');
    //   }
    // };
  }

  rtpSocket.prototype.onerror = function(){
    var self = this;
    self.offMouseEvent(); 
    self.ws.onerror = function(e){
     console.log('rtpSocket 错误', e);
    }
  }

  rtpSocket.prototype.accessRtp = function(sendflag){
  	if(this.cid && this.sid){
  	  this.send(fnRtpSocketHandler.getAccessRtpMsg(this.cid, this.sid, this.uid, 
  	  	this.destip, this.destport, this.payloadtype, sendflag));
  	}//6
  }

  rtpSocket.prototype.startSendRtp = function(){
    if(this.cid && this.sid){
      this.send(fnRtpSocketHandler.getSendRtpMsg(this.sid, this.cid, 1));
    }
  }

  rtpSocket.prototype.stopSendRtp = function(){
    if(this.cid && this.sid){
      this.send(fnRtpSocketHandler.getSendRtpMsg(this.sid, this.cid, 0));
    }
  }

  rtpSocket.prototype.exitRtp = function(){
    if(this.cid && this.sid){
      this.send(fnRtpSocketHandler.getStopRtpMsg(this.sid, this.cid));
    }
  }

  rtpSocket.prototype.setPttKeyboard = function(code){
    this.pttKey = code;
  }

  rtpSocket.prototype.onPttKeyDown = function(){
    var self = this;
    var audio = document.getElementById('ptt_music');

    $(document).one('keydown',function(e){
      if(e.which === self.pttKey){
        startPtt(self, audio);
      }
    });
  }

  rtpSocket.prototype.onPttKeyUp = function(){

    var self = this;
    var audio = document.getElementById('ptt_music');

    $(document).on('keyup', function(e){
      if(e.which === self.pttKey){
        self.onPttKeyDown();
        stopPtt(self, audio);
      }
    });
  }

  rtpSocket.prototype.offPttKey = function(){
    $(document).off('keydown');
    $(document).off('keyup');
  }

  var startPtt = function(container, audio){
    //audio.pause();
    if(container.recvPtt === 1){
      $('#ptt-btn').addClass('ptt-down');
      $('#ptt-button').attr('src','images/talk_leisure_down.png');
      $('#curr_status').removeClass('ptt-status-free')
        .removeClass('ptt-status-speeking')
        .addClass('ptt-status-forbidden');
      if(audio){
        audio.src = 'media/ptt_down_fail_0921.ogg';
        setTimeout(function () {      
          if (audio.paused) {
            audio.play();
          }
        }, 100);
      }
    }else{
      $('#ptt-button').attr('src','images/talk_leisure_down.png');
      $('#ptt-btn').addClass('ptt-down');
      $('#curr_status').removeClass('ptt-status-free')
        .removeClass('ptt-status-forbidden')
        .addClass('ptt-status-speeking');
      $('#ptt_member_span').html('');
      $('#ptt_status_span').html('我正在发言');
      $('#ptt-status-i').html('发言中');
      $('.status-content .content-right i.icon').css('background','url(images/talking_reminder.png) no-repeat');
      $('#ptt-status-p').html('本机在发言');
      container.startSendRtp();
    }
    
  }

  var stopPtt = function(container, audio){
    audio.pause();
    $('#ptt-btn').removeClass('ptt-down');
    console.log(container);
    if(container.recvPtt === 1){
      //$('#ptt-button').attr('src','images/talk_leisure.png');
      $('#curr_status').removeClass('ptt-status-free')
        .removeClass('ptt-status-speeking')
        .addClass('ptt-status-forbidden');
    }else{
      $('#ptt-button').attr('src','images/talk_leisure.png');
      $('#curr_status').removeClass('ptt-status-speeking')
        .removeClass('ptt-status-forbidden')
        .addClass('ptt-status-free');
        $('#ptt_member_span').html('');
      $('#ptt-status-i').html('空闲');
      $('.status-content .content-right i.icon').css('background','url(images/talk_reminder.png) no-repeat');
      $('#ptt-status-p').html('');
        $('#ptt_status_span').html('空闲');
        container.stopSendRtp();
    }
    $('#ptt-btn').off('mouseout');
  }

  rtpSocket.prototype.onMouseEvent = function(){
    var self = this;
    $('#ptt_status_img').attr('src', 'images/free.png');
    $('#ptt_member_span').html('');
    $('#ptt_status_span').html('空闲');
    var audio = document.getElementById('ptt_music');

    if(fnUtils.isPC()){
      // PTT按键按下状态
      $('#ptt-btn').on('mousedown', function(){
        startPtt(self, audio);
        $('#ptt-btn').on('mouseout', function(){
          stopPtt(self, audio);
        });
      });
      // PTT按键放开状态
      $('#ptt-btn').on('mouseup', function(){
        stopPtt(self, audio);
      });
      //界面调整后
      $('#ptt-button').on('mousedown', function(){
        startPtt(self, audio);
        $('#ptt-button').on('mouseout', function(){
          if($('#ptt-status-i').html()=='发言中'){
            stopPtt(self, audio);
          }
        });
      });
      $('#ptt-button').on('mouseup', function(){
        stopPtt(self, audio);
      });
    }else{
      document.getElementById('ptt-btn').addEventListener('touchstart', function (e){
        e.preventDefault();
        startPtt(self, audio);
      });
      document.getElementById('ptt-btn').addEventListener('touchend',function (e){
        e.preventDefault();
        stopPtt(self, audio);
      });
      //ui界面调整后
      document.getElementById('ptt-button').addEventListener('touchstart', function (e){
        e.preventDefault();
        startPtt(self, audio);
      });
      document.getElementById('ptt-button').addEventListener('touchend',function (e){
        e.preventDefault();
        stopPtt(self, audio);
      });
    }
  }

  rtpSocket.prototype.offMouseEvent = function(){
    $('#ptt-btn').off('mousedown');
  }
  return rtpSocket;
});